const fs = require("fs")
const service = require("../service/moment.service")
const fileService = require("../service/file.service")
const {PICTURE_PATH} = require("../contants/file-path")

class momnetConstroller {
  async create(ctx,next){
    //1.获取数据(user_id,content)
    const userId = ctx.user.id;
    const {content} = ctx.request.body;

    //2.将数据插入到我们的数据库里边
    const result = await service.create(userId,content)
    ctx.body = result
  }

  //获取单条动态的数据
  async detail(ctx,next){
    //1.获取数据(moentId)
    const {momentId} = ctx.request.params

    //2.根据id 获取数据
    const result = await service.getMomentById(momentId)
    ctx.body = result
  }

  //获取动态列表
  async list(ctx,next){
    //1.获取offset和 size
    const {offset,size} = ctx.request.query;

    //2.查询列表
    const result = await service.getMomentList(offset,size);
    ctx.body = result
  }

  async update(ctx,next) {
    //1. 获取参数
    const {momentId} = ctx.request.params
    const {content} = ctx.request.body

    //2. 修改内容
    const result = await service.update(content,momentId)
    ctx.body = result
  }

  async remove(ctx,next) {
    //1.获取momentId
    const {momentId} = ctx.request.params;
    const result = await service.remove(momentId)
    ctx.body = result;
  }

  async addLabel(ctx,next) {
    //获取标签和动态id
    const {labels} = ctx
    const {momentId} = ctx.request.params

    for (const label of labels) {
      const isExist = await service.hasLabelByComment(label.id,momentId)
      if(!isExist){
        await service.addLabel(label.id,momentId)
      }
    }

    ctx.body = "给动态添加标签成功"
  }


  async fileInfo(ctx,next){
    const {filename} = ctx.request.params
    const fileInfo = await fileService.getFileByFilename(filename)
    ctx.response.set('content-type',fileInfo.mimetype)
    // const { type } = ctx.query;
    // const types = ["small", "middle", "large"];
    // if (types.some(item => item === type)) {
    //   filename = filename + '-' + type;
    // }
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
  }
}

module.exports = new momnetConstroller()